CQCIS.form.DWRForm = function(config) {
    this.waitMsgTarget = true;
    Ext.apply(this, config);
    
    this.baseParams = this.baseParams ? this.baseParams : {};
    this.extendParams = [];
    this.doing = false;
    CQCIS.form.DWRForm.superclass.constructor.call(this);
};

Ext.extend(CQCIS.form.DWRForm, Ext.FormPanel, {
    /**
     * @cfg {dwr} DWR call
     *
     * <pre>
     * 属性      描述
     * ---------dwr----------------
     * load     加载
     * save     保存
     * update   更新
     * </pre>
     *
     */
    labelWidth: 60,
    border: false,
    bodyStyle: 'padding:5px;',
    defaults: {
        anchor: '90%',
        msgTarget: 'side',
        labelSeparator: ''
    },
    defaultType: 'textfield',
    
    initComponent: function() {
        CQCIS.form.DWRForm.superclass.initComponent.call(this);
        
        this.addEvents({
            /**
             * @event on load
             */
            "beforeload": true,
            "loadafter": true,
            /**
             * @event on save
             */
            "beforesave": true,
            "saveafter": true
        });
    },
    
    getDs: function() {
        if (this.dwr && !this.ds) {
            var fieldObj = this.getValues(), fields = [];
            for (var filed in fieldObj) {
                fields.push(filed);
            }
            
            this.ds = new CQCIS.data.DWRStore({
                dwr: {
                    call: this.dwr.load,
                    save: this.dwr.save ? this.dwr.save : this.dwr.update,
                    update: this.dwr.update ? this.dwr.update : this.dwr.save
                },
                fields: fields,
                ownerCt: this
            });
            
            this.ds.on('load', function(scope, recodes) {
                var recode = recodes[0];
                var data = recode ? recode.data : {};
                this.form.setValues(data);
                this.afterRemote();
                this.fireEvent('loadafter', data, this, scope);
            }, this);
            
            this.ds.on('save', function(scope, o) {
                this.afterRemote();
                this.fireEvent('saveafter', o, this, scope);
                this.onSaveafter(o);
            }, this);
        }
        
        return this.ds;
    },
    
    // private
    beforeRemote: function(waitMsg) {
        if (waitMsg) {
            if (this.waitMsgTarget === true) {
                this.el.mask(waitMsg, 'x-mask-loading');
            } else if (this.waitMsgTarget) {
                this.waitMsgTarget = Ext.get(this.waitMsgTarget);
                this.waitMsgTarget.mask(waitMsg, 'x-mask-loading');
            } else {
                Ext.MessageBox.wait(waitMsg, '请稍候...');
            }
            this.doing = true;
        }
    },
    
    // private
    afterRemote: function(action, success) {
        if (this.doing) {
            if (this.waitMsgTarget === true) {
                this.el.unmask();
            } else if (this.waitMsgTarget) {
                this.waitMsgTarget.unmask();
            } else {
                Ext.MessageBox.updateProgress(1);
                Ext.MessageBox.hide();
            }
            this.doing = false;
        }
    },
    
    // private
    doRemote: function(action) {
        var valid = this.form.isValid();
        if (!valid) {
            CQCIS.msg('字段校验没通过,请查看窗口字段提示信息!');
        } else {
            this.beforeRemote('正在保存数据...');
            if (this.fireEvent("beforesave", this) !== false) {
                var arg = [];
                if (this.findByType('datefield').length > 0) {
                    var dateFields = this.findByType('datefield');
                    var values = this.getValues();
                    for (var i = 0; i < this.findByType('datefield').length; i++) {
                        if (dateFields[i].dataType != 'String') {
                            values[dateFields[i].name] = dateFields[i].getValue() === '' ? null : dateFields[i].getValue();
                        }
                    }
                    arg = [values];
                } else if (this.findByType('datetimefield').length > 0) {
                    var dateTimeFields = this.findByType('datetimefield');
                    var values = this.getValues();
                    for (var i = 0; i < this.findByType('datetimefield').length; i++) {
                        if (dateTimeFields[i].dataType != 'String') {
                            values[dateTimeFields[i].name] = dateTimeFields[i].getValue() === '' ? null : dateTimeFields[i].getValue();
                        }
                    }
                    arg = [values];
                } else {
                    arg = [this.getValues()];
                }
                if (this.extendParams.length > 0) {
                    arg = arg.concat(this.extendParams);
                }
                this.getDs()[action]({
                    arg: arg
                });
            } else {
                this.afterRemote();
            }
        }
    },
    
    /**
     * @param params
     *
     * <pre>
     * null
     * 代表新增
     * object/array  修改
     * </pre>
     */
    load: function(params) {
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            if (params) {
                this.beforeRemote('正在读取数据...');
                params = params instanceof Array ? params : [params];
                if (this.fireEvent("beforeload", this, params) !== false) {
                    this.form.reset();
                    this.getDs().load({
                        arg: params
                    });
                }
            } else {
                this.form.isValid(); // 增加校验提示
            }
        }
    },
    getValues: function(asString) {
        var obj = {};
        for (var i = 0; i < this.items.length; i++) {
            var f = this.items.get(i);
            if (f.getName().indexOf("_") === 0) {
                continue;
            } else if (f.getXType() == 'radio') {
                obj[f.getName()] = f.getGroupValue();
            } else if (f.getXType() == 'hidden' && f.type == 'date') {
                obj[f.getName()] = f.getValue() ? new Date(f.getValue()) : new Date();
            } else {
                obj[f.getName()] = f.getValue();
            }
        }
        if (asString) {
            obj = Ext.urlEncode(obj);
        }
        if (this.baseParams && typeof this.baseParams == 'object') {
            if (asString) {
                obj = obj + '&' + Ext.urlEncode(this.baseParams);
            } else {
                Ext.apply(obj, this.baseParams);
            }
        }
        
        return obj;
    },
    /**
     * @param params
     *            FORM提交时基础属性
     */
    save: function() {
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            this.doRemote('save');
        }
    },
    update: function() {
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            this.doRemote('update');
        }
    },
    setExtendParams: function(parms) {
        this.extendParams = [];
        if (parms instanceof Array) {
            this.extendParams = this.extendParams.concat(parms);
        } else {
            this.extendParams.push(parms);
        }
    },
    onSaveafter: function(data) {
        if (this.afterSubmit && this.afterSubmit instanceof Function) {
            this.afterSubmit(data);
        }
        CQCIS.msg('表单提交完成！');
        this.ownerCt.hide();
    }
});
Ext.reg('rform', CQCIS.form.DWRForm);
